package com.yegs.jltqc.controller;

import com.yegs.jltqc.TO.NamePageQuery;
import com.yegs.jltqc.VO.BaseUser;
import com.yegs.jltqc.common.StoreException;
import com.yegs.jltqc.config.ConcurentCache;
import com.yegs.jltqc.config.Msg;
import com.yegs.jltqc.service.BaseUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;


@RestController
@RequestMapping("/baseUser")
public class BaseUserController {

    @Autowired
    private BaseUserService baseUserService;

    @PostMapping("/login")
    public Msg login(@RequestParam(value = "username",required = true) String username,
                     @RequestParam(value = "password",required = true) String password){
        try{
            BaseUser user = baseUserService.findByCodeAndPassword(username, password);
            if(user == null){
                user = baseUserService.findByUsernameAndPassword(username, password);
            }
            if(user==null){
                return Msg.error("密码错误!");
            }else {
                return  Msg.success("token",user.getId());
            }
        }catch (Exception e){
            e.printStackTrace();
            return Msg.error(e.getMessage());
        }
    }

    @GetMapping("/info")
    public Msg info(@RequestParam String token){
        try{
            if(token==null){
                return Msg.noPermission();
            }else {
                BaseUser baseUser = baseUserService.get(Long.parseLong(token));
                HashMap hashMap = new HashMap();
                hashMap.put("name", baseUser.getUsername());
                hashMap.put("avatar", "");
                hashMap.put("roles","admin".equals(baseUser.getUsername())? "admin" : baseUser.getMenus().size() == 0
                        ? "common":baseUser.getMenus());
                return  Msg.success(hashMap);
            }
        }catch (Exception e){
            e.printStackTrace();
            return Msg.error(e.getMessage());
        }
    }

    @GetMapping("/get")
    public Msg get(){
        return Msg.success("data",ConcurentCache.getLoginUser());
    }

    @PostMapping("/logout")
    public Msg login(String token){
        return Msg.success("清除token成功");
    }
    @PostMapping("/query")
    public Msg query(@RequestBody NamePageQuery query){
        return Msg.success("page",baseUserService.query(query));
    }



    @PostMapping("/save")
    public Msg save(@RequestBody BaseUser baseUser){
        try {
            baseUserService.save(baseUser);
        } catch (StoreException e) {
            return Msg.error(e.getMessage());
        }
        return Msg.success();
    }

    @GetMapping("/del")
    public Msg del(@RequestParam Long id){
        baseUserService.del(id);
        return Msg.success();
    }


}
